package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class HandlerDivide extends Activity {
	int mainValue;
	TextView mainTv;
	TextView backTv;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_threadex);

		mainTv = (TextView) findViewById(R.id.ch19_threadex_mainvalue);
		backTv = (TextView) findViewById(R.id.ch19_threadex_backvalue);

		BackThread thread = new BackThread(mHandler);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void mOnClick(View v) {
		if (v.getId() == R.id.ch19_threadex_increase) {
			mainValue++;
			mainTv.setText("MainValue : " + mainValue);
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				backTv.setText("BackValue : " + msg.arg1);
			}
		};
	};
}

class BackThread extends Thread {
	int backValue;
	Handler mHandler;

	public BackThread(Handler mHandler) {
		super();
		this.mHandler = mHandler;
	}

	public void run() {
		while (true) {
			backValue++;
			/*Message msg = new Message();
			msg.what = 0;
			msg.arg1 = backValue;
			mHandler.sendMessage(msg);*/
			
			Message msg = Message.obtain(mHandler, 0, backValue, 0);
			mHandler.sendMessage(msg);
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}